﻿using System;
using System.Collections;
using System.Globalization;

using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Data;

using System.Web.Security;
using System.Web;
using SpringWaterDataAccess;


namespace Utilities
{
	/// <summary>
	/// Summary description for Helper.
	/// </summary>
	public class Helper
	{
		private static Hashtable CategoryLocations = new Hashtable();
		private static Hashtable CategoryMappings = new Hashtable();
		private static Hashtable PartnerMappings = new Hashtable();
 
		static Helper()
		{
			/*CategoryLocations.Add("1","/content/edited/jianzheng"); //信的故事
			CategoryLocations.Add("2","/content/edited/zhishi"); //圣经知识
			CategoryLocations.Add("3","/content/edited/wenhua"); //文化信仰
			CategoryLocations.Add("4","/content/edited/jiating"); //婚姻家庭
			CategoryLocations.Add("5","/content/edited/yinyue");  //音乐赞美
			CategoryLocations.Add("6","/content/edited/longwen"); //交通
			CategoryLocations.Add("7","/content/edited/yunjie");  //云姐信箱
			CategoryLocations.Add("8","/content/edited/xiaopin");  //福音小品

			CategoryMappings.Add("1","信的故事"); //信的故事
			CategoryMappings.Add("2","圣经知识"); //圣经知识
			CategoryMappings.Add("3","文化信仰"); //文化信仰
			CategoryMappings.Add("4","婚姻家庭"); //婚姻家庭
			CategoryMappings.Add("5","赞美诗歌");  //音乐赞美
			CategoryMappings.Add("6","交通"); //交通
			CategoryMappings.Add("7","晓云信箱");  //晓云信箱
			CategoryMappings.Add("8","福音小品");  //福音小品*/

	   }

        public static string GetSubString(object obj, int len) 
        {
            String str = Convert.ToString(obj);

            if (str == null || str == "")
            {
                return "";
            }

            if (str.Length <= len)
            {
                return str;
            }

            return str.Substring(0, len);

        }

		public static string getLocationFromCategory(string category)
		{
			//return (string)CategoryLocations[category];
			SQLAccess sql = new SQLAccess();
			int cid = Convert.ToUInt16(category);
			DataSet cds = sql.getCategory(cid);

			return Convert.ToString(cds.Tables[0].Rows[0]["Location"]);
		}

		public static string getCategoryFromID(string id)
		{
			//return (string)CategoryMappings[id];
			SQLAccess sql = new SQLAccess();
			int cid = Convert.ToUInt16(id);
			DataSet cds = sql.getCategory(cid);

			return Convert.ToString(cds.Tables[0].Rows[0]["CategoryCode"]);
		}

        public static string GetURL(string filename) 
        {		
            if (filename == null || filename == "")
            {
                return "";
            }
            return "<A href= 'data\\" + filename + "' style=text-decoration:none><font color=\"#0033ff\">点击下载多媒体文件</font></A>";
        }

        public static string formatDate(object dateObj) 
		{
		
			if (dateObj == null || dateObj.Equals("")) 
			{
				return "";
			}

			string dateStr = System.Convert.ToString(dateObj);

			if (dateStr != "") 
			{
				DateTime myDateTime = DateTime.Parse(dateStr);
				return myDateTime.Month + "/" + myDateTime.Year;
			} 
			else 
			{
				return dateStr;
			}
		}

		public static string formatDateDDMMYY(object dateObj) 
		{
		
			if (dateObj == null || dateObj.Equals("")) 
			{
				return "";
			}

			string dateStr = System.Convert.ToString(dateObj);

			if (dateStr != "") 
			{
				DateTime myDateTime = DateTime.Parse(dateStr);
				return myDateTime.ToString("d");
			} 
			else 
			{
				return dateStr;
			}
		}

		
		public static string ConvertDate(string Date, string UserLanguage)
		{
			CultureInfo ci = new CultureInfo(UserLanguage,false);
			DateTimeFormatInfo dtFormat = ci.DateTimeFormat;
			DateTime dt = System.Convert.ToDateTime(Date);
			return dt.ToLongDateString();
		}

		public static string FindLeadingWords(string str, int num) 
		{
			return str.Substring(0,Math.Min(num,str.Length));

		}

		// Check if the userID from URL matches the one who is currently logged in
		public static bool IdentifyUser(System.Web.HttpRequest request)
		{
			System.Web.HttpCookie emailCookie = request.Cookies["Email"];
			string userID = request.QueryString["UserID"];

			DataSet userDataSet = UserObject.GetUserByID(Convert.ToUInt16(userID));
		
			string userEmail = Convert.ToString(userDataSet.Tables[0].Rows[0]["Email"]);
 
			return (emailCookie != null) && (userEmail == emailCookie.Value);
		}

		//FJC = First Join Column

		//SJC = Second Join Column

		public static DataTable Join (DataTable First, DataTable Second, DataColumn[] FJC, DataColumn[] SJC)

		{

			//Create Empty Table

			DataTable table = new DataTable("Join");

			// Use a DataSet to leverage DataRelation

			using(DataSet ds = new DataSet())

			{

				//Add Copy of Tables

				ds.Tables.AddRange(new DataTable[]{First.Copy(),Second.Copy()});

				//Identify Joining Columns from First

				DataColumn[] parentcolumns = new DataColumn[FJC.Length];

				for(int i = 0; i < parentcolumns.Length; i++)

				{

					parentcolumns[i] = ds.Tables[0].Columns[FJC[i].ColumnName];

				}

				//Identify Joining Columns from Second

				DataColumn[] childcolumns = new DataColumn[SJC.Length];

				for(int i = 0; i < childcolumns.Length; i++)

				{

					childcolumns[i] = ds.Tables[1].Columns[SJC[i].ColumnName];

				}

				//Create DataRelation

				DataRelation r = new DataRelation(string.Empty,parentcolumns,childcolumns,false);

				ds.Relations.Add(r);

				//Create Columns for JOIN table

				for(int i = 0; i < First.Columns.Count; i++)

				{

					table.Columns.Add(First.Columns[i].ColumnName, First.Columns[i].DataType);

				}

				for(int i = 0; i < Second.Columns.Count; i++)

				{

					//Beware Duplicates

					if(!table.Columns.Contains(Second.Columns[i].ColumnName))

						table.Columns.Add(Second.Columns[i].ColumnName, Second.Columns[i].DataType);

					else

						table.Columns.Add(Second.Columns[i].ColumnName + "_Second", Second.Columns[i].DataType);

				}

				//Loop through First table

				table.BeginLoadData();

				foreach(DataRow firstrow in ds.Tables[0].Rows)

				{

					//Get "joined" rows

					DataRow[] childrows = firstrow.GetChildRows(r);

					if(childrows != null && childrows.Length > 0)

					{

						object[] parentarray = firstrow.ItemArray;

						foreach(DataRow secondrow in childrows)

						{

							object[] secondarray = secondrow.ItemArray;

							object[] joinarray = new object[parentarray.Length+secondarray.Length];

							Array.Copy(parentarray,0,joinarray,0,parentarray.Length);

							Array.Copy(secondarray,0,joinarray,parentarray.Length,secondarray.Length);

							table.LoadDataRow(joinarray,true);

						}

					}

				}

				table.EndLoadData();

			}

			return table;

		}

		public static DataTable Join (DataTable First, DataTable Second, DataColumn FJC, DataColumn SJC)

		{

			return Join(First, Second, new DataColumn[]{FJC}, new DataColumn[]{SJC});

		}

		public static DataTable Join (DataTable First, DataTable Second, string FJC, string SJC)

		{

			return Join(First, Second, new DataColumn[]{First.Columns[FJC]}, new DataColumn[]{First.Columns[SJC]});

		}

	}
}
